package com.hyb.hybmodulesfront.controller;

import com.alibaba.fastjson2.JSON;
import com.hyb.hybmodulesfront.beans.vo.OssVo;
import com.ruoyi.common.core.constant.ArticleConstant;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.file.ImageUtils;
import com.ruoyi.common.core.utils.sign.Base64;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.*;
import com.ruoyi.system.api.domain.Article;
import com.ruoyi.system.api.domain.SchoolRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.domain.UserDetail;
import com.ruoyi.system.api.model.LoginUser;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    RemoteArticleService remoteArticleService;

    @Autowired
    RemoteSearchService remoteSearchService;


    @Autowired
    RemoteOssService remoteOssService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    RemoteUserService userService;

    @Autowired
    RemoteUserDetailService detailService;

    @Autowired
    RemoteSchoolRoleService remoteSchoolRoleService;


    /*
    * 前台发布文章
    * */
    @PostMapping("/publish")
    public AjaxResult publish(@RequestBody Article article, @RequestParam("isPublish")Boolean isPublish){
        String text=article.getPf1();
        if (StringUtils.isEmpty(text)){
            return AjaxResult.error("文章不能为空");
        }
        OssVo ossVo = new OssVo();
        ossVo.setValue(text);
        //远程调用插入oss
        AjaxResult upText = remoteOssService.upText(JSON.toJSONString(ossVo), ".txt", SecurityConstants.INNER);
        if (upText.isError()){
            throw new GlobalException("txt文件上传至oss失败");
        }

        article.setContentUrl((String) upText.get("url"));

        //发布为草稿
        if(!isPublish){
            article.setStatus(ArticleConstant.DRAFT_STATUS);
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();

        if (loginUser==null){
            throw  new GlobalException("获取用户信息异常");
        }
        SysUser sysUser = loginUser.getSysUser();
        if (sysUser==null){
            throw new GlobalException("获取用户信息异常");
        }

        article.setUserId(sysUser.getUserId());
        article.setUserName(sysUser.getUserName());
        article.setUseNickName(sysUser.getNickName());
        article.setUpdateTime(DateUtils.getNowDate());
        article.setPublishTime(DateUtils.getNowDate());
        article.setPf1(null);
//        ossVo.setValue(article.getArticleDes());


        String encode = Base64.encode(article.getArticleDes().getBytes(StandardCharsets.UTF_8));
        redisTemplate.opsForValue().set(ArticleConstant.DESC_KEY+sysUser.getUserId(), encode);
        article.setArticleDes(null);
        //远程调用插入文章表
        AjaxResult ajaxResult = remoteArticleService.addInner(article, SecurityConstants.INNER);

        //远程调用插入es
        if (ajaxResult.isError()){
            throw new GlobalException("插入文章表失败");
        }
        //如果是发布文章,就上传到elastic服务器里
        if(isPublish){
            Integer id= (Integer) ajaxResult.get("id");
            article.setId(Long.parseLong(id+""));
            article.setCollectionCount(0L);
            article.setCommenCount(0L);
            article.setThumbCount(0L);
            article.setTrampleCount(0L);
            article.setArticleHot(0L);
            article.setThumbCount(0L);


            AjaxResult add = remoteSearchService.add(article, SecurityConstants.INNER);
            if (add.isError()){
                throw new GlobalException("插入elastic失败");
            }
        }

        return AjaxResult.success();
    }


    @GetMapping("/info")
    public AjaxResult getInfo(@RequestParam("id")String id){

        //再获取用户的文章信息
        R<Article> articleR = remoteArticleService.get(Long.parseLong(id), SecurityConstants.INNER);
        Article article = articleR.getData();
        //利用文章信息将文章查询出来
        byte[] bytes = ImageUtils.readFile(article.getContentUrl());
        String text= bytes==null?"":new String(bytes);


        Long userId = article.getUserId();

        //先查询用户信息
        R<SysUser> sysUserInfo = userService.getSysUserInfo(userId, SecurityConstants.INNER);
        SysUser data = sysUserInfo.getData();
        if (data==null){
            return AjaxResult.error("获取用户信息错误");
        }
        //再获取用户细节信息
        R<UserDetail> innerPersonal = detailService.getInnerPersonal(userId, SecurityConstants.INNER);
        UserDetail userDetail = innerPersonal.getData();

        //再获取用户学校信息
        R<SchoolRole> personalSchoolRole = remoteSchoolRoleService.getPersonalSchoolRole(userId, SecurityConstants.INNER);
        SchoolRole role = personalSchoolRole.getData();



        Map<String,Object> map=new HashMap<>();
        map.put("sys",sysUserInfo);
        map.put("detail",userDetail);
        map.put("role",role);
        map.put("article",article);
        map.put("text",text);

        return AjaxResult.success().put("map",map);

    }

}
